package com.focus.wecenter.web.controller;

import com.focus.wecenter.service.UserService;
import com.focus.wecenter.service.ArticleService;
import com.focus.wecenter.service.QuestionService;
import com.focus.wecenter.service.TopicService;
import com.focus.wecenter.util.FunUtil;
import com.focus.wecenter.util.Message;
import com.focus.wecenter.web.controller.common.BaseController;
import com.focus.wecenter.web.vo.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 搜索控制器
 *
 * @author Lv Jing
 * @date 2018年01月07日 21:07
 */
@Controller
@RequestMapping("/search")
public class SearchController extends BaseController {

    @Autowired
    private QuestionService questionService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;

    /**
     * 搜索问题
     * @param type 搜索类型
     * @param query 查询关键字
     * @param limit 查询条数
     */
    @RequestMapping(value = "/ajax/search", method = RequestMethod.GET)
    @ResponseBody
    public Message searchQuestion(String type, @RequestParam("q") String query, int limit) {
        Message message = new Message();
        if (FunUtil.isEmpty(query)) {
            return message;
        }
        query = query.trim();
        List<SearchResult> results;
        if (type == null) {
            type = "search";
        }
        switch (type) {
            case "questions":
                results = questionService.searchQuestion(query, limit);
                break;
            case "topics":
                results = topicService.searchTopic(query, limit);
                break;
            default:
                results = userService.searchUser(query, limit);
                results.addAll(topicService.searchTopic(query, limit));
                results.addAll(questionService.searchQuestion(query, limit));
                results.addAll(articleService.searchArticle(query, limit));
        }
        message.setData(results);
        return message;
    }
}
